/******************************************************************************************
 * Copyright(c) 2011-2020 SK Telecom All rights reserved.
 *  This software is the proprietary information of SK Telecom Network Information System
 *  Revision History 
 *  
 *  Author   Date            Description
 *  ------   ----------      ------------------------------------
 *  이기정        2012. 8. 14.    First Draft.
 *  형상관리도구를 사용하므로 Comment로는 First Draft 만 표기하도록 규정합니다.
 * 
 ******************************************************************************************/
package com.skcc.ts.nsi.expense;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TableRow;
import com.skcc.ts.nsi.R;
import com.skcc.ts.nsi.service.MEDataHandler;
import com.skcc.ts.nsi.service.MEDateHandler;
import com.skcc.ts.nsi.service.SocketClientService;

/**
 * <b>클래스 명 :</b> <b>MEExpenseListSearch</b>
 * <p>
 * <b>용도:</b>
 * <ul>
 * <li>정산내역 조회화면
 * <li>클래스 사용 용도 방법을 여기에 기입합니다. 용도2번
 * <li>아래와 같은 태그 사용가능
 * <li>({@link 링크할 소스})<code>String str = "코드입력부분";</code>
 * </ul>
 * </p>
 * 
 * @author <a href="mailto:jellyfishlove@sk.com">이기정</a>
 * @since 2012. 8. 14.
 */
public class MEExpenseListSearch extends Activity {

	private ArrayList<String[]> pjtList = null;
	private ArrayList<String[]> acntList = null;
	private Button btn_expense_list_show;
	private ImageButton btn_expense_calendar_start;
	private ImageButton btn_expense_calendar_end;
	private Button btn_expense_list_today;
	private Button btn_expense_list_week;
	private Button btn_expense_list_month;
	private EditText startDate;
	private EditText endDate;
	private int mYear;
	private int mMonth;
	private int mDay;
	// private int expSearchid = 42; //
	private String myId;
	private String selectedPjt;
	private String selectedAcnt;
	private String pjtCode;
	private String acntCode;
	private String addr;
	private String port;

	static final int DATE_DIALOG_CALENDAR_START = 1;
	static final int DATE_DIALOG_CALENDAR_END = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.meexpense_list_search);

		// 기간조회를 위한 초기 날짜값 설정
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);

		doListExpense();// 프로젝트정보수집
		initButtons();// 버튼 세팅
		initSpinners();// 스니퍼 동적생성

	}

	private void doListExpense() {
		Intent receiveI = getIntent();
		boolean doYN = receiveI.getBooleanExtra("start", false);
		if (doYN) {
			boolean reset = receiveI.getBooleanExtra("setAcnt", false);
			myId = receiveI.getStringExtra("myId");
			addr = receiveI.getStringExtra("loginAddr");
			port = receiveI.getStringExtra("loginPort");
			pjtList = new ArrayList<String[]>();
			acntList = new ArrayList<String[]>();
			String pCode = "-- 선택 --,";
			String pName = "-- 선택 --,";
			String aCode = "-- 선택 --,";
			String aName = "-- 선택 --,";
			if (reset) {
				String selection = receiveI.getStringExtra("selection");
				if ("noacnt".equals(selection)) {
					new AlertDialog.Builder(MEExpenseListSearch.this).setTitle("알림").setMessage("프로젝트 내 해당계정이 없습니다.")
							.setPositiveButton("OK", null).show();
				} else if ("nodata".equals(selection)) {
					new AlertDialog.Builder(MEExpenseListSearch.this).setTitle("알림").setMessage("조회기간 내 정산내역이 없습니다.")
							.setPositiveButton("OK", null).show();
				}
			}
			String[] pjt_code = receiveI.getStringArrayExtra("projectCode");
			String[] pjt_name = receiveI.getStringArrayExtra("projectName");
			String[] acnt_code = receiveI.getStringArrayExtra("accountCode");
			String[] acnt_name = receiveI.getStringArrayExtra("accountName");
			for (int i = 0; i < pjt_code.length; i++) {
				pCode = pCode.concat(pjt_code[i] + ",");
				pName = pName.concat(pjt_name[i] + ",");
			}
			for (int i = 0; i < acnt_code.length; i++) {
				aCode = aCode.concat(acnt_code[i] + ",");
				aName = aName.concat(acnt_name[i] + ",");
			}
			String[] pjtCode = MEDataHandler.checkArray(pCode);
			String[] pjtName = MEDataHandler.checkArray(pName);
			String[] acntCode = MEDataHandler.checkArray(aCode);
			String[] acntName = MEDataHandler.checkArray(aName);

			pjtList.add(0, pjtCode);
			pjtList.add(1, pjtName);
			acntList.add(0, acntCode);
			acntList.add(1, acntName);
		}
	}

	private void initSpinners() {// 스피너 세팅
		final String[] pjtSnipper = pjtList.get(1);
		final String[] acntSnipper = acntList.get(1);
		ArrayAdapter<String> adapter_pjt = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, pjtSnipper);
		ArrayAdapter<String> adapter_acnt = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, acntSnipper);
		Spinner sp_pjt = (Spinner) findViewById(R.id.spinner_expense_list_pjtlist);
		adapter_pjt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp_pjt.setAdapter(adapter_pjt);

		sp_pjt.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				selectedPjt = pjtSnipper[position];
				pjtCode = pjtList.get(0)[position];

			}

			public void onNothingSelected(AdapterView<?> parent) {
				selectedPjt = "-- 선택 --";
			}

		});

		Spinner sp_acnt = (Spinner) findViewById(R.id.spinner_expense_list_acntlist);
		adapter_acnt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp_acnt.setAdapter(adapter_acnt);

		sp_acnt.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				selectedAcnt = acntSnipper[position];
				acntCode = acntList.get(0)[position];
			}

			public void onNothingSelected(AdapterView<?> parent) {
				selectedAcnt = "-- 선택 --";
			}
		});

	}

	/**
	 * <b>메소드 :</b> <b>메소드 한글/영문 명을 여기에 기입합니다.</b>
	 * <p>
	 * <ul>
	 * <li>버튼 이벤트 정리
	 * </ul>
	 * </p>
	 * 
	 * @since 2012. 8. 14.
	 */
	private void initButtons() {
		btn_expense_list_show = (Button) findViewById(R.id.btn_expense_list_show); // 정산내역조회버튼
		btn_expense_calendar_start = (ImageButton) findViewById(R.id.btn_expense_calendar_start); // 달력(from)버튼
		btn_expense_calendar_end = (ImageButton) findViewById(R.id.btn_expense_calendar_end);// 달력(to)버튼
		btn_expense_list_today = (Button) findViewById(R.id.btn_expense_list_today);// 당일조회
		btn_expense_list_week = (Button) findViewById(R.id.btn_expense_list_week);// 일주일조회
		btn_expense_list_month = (Button) findViewById(R.id.btn_expense_list_month);// 한달조회
		startDate = (EditText) findViewById(R.id.editText_expense_start_date);
		endDate = (EditText) findViewById(R.id.editText_expense_end_date);

		// 달력기간설정(from)
		btn_expense_calendar_start.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// 날짜 입력 위젯 띄우기
				showDialog(DATE_DIALOG_CALENDAR_START);
			}
		});

		// 달력기간설정(to)
		btn_expense_calendar_end.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// 날짜 입력 위젯 띄우기
				showDialog(DATE_DIALOG_CALENDAR_END);
			}
		});

		// 당일조회
		btn_expense_list_today.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String today = MEDateHandler.calcToday();
				startDate.setText(today);
				endDate.setText(today);
			}
		});

		// 일주일 조회
		btn_expense_list_week.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String today = MEDateHandler.calcToday();
				String oldDay = MEDateHandler.calcOldDay(-7);
				startDate.setText(oldDay);
				endDate.setText(today);
			}
		});

		// 한달 조회
		btn_expense_list_month.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String today = MEDateHandler.calcToday();
				String oldDay = MEDateHandler.calcOldDay(-30);
				startDate.setText(oldDay);
				endDate.setText(today);
			}
		});

		// 정산내역 조회
		btn_expense_list_show.setOnClickListener(new View.OnClickListener() {
			public void onClick(View arg0) {

				String fromDay = null;
				String toDay = null;
				fromDay = startDate.getText().toString();
				toDay = endDate.getText().toString();
				if (fromDay == null || fromDay.equals("") || toDay == null || toDay.equals("")) {
					new AlertDialog.Builder(MEExpenseListSearch.this).setTitle("알림").setMessage("기간을 설정하여 주십시오")
							.setPositiveButton("OK", null).show();
				} else if (fromDay.compareTo(toDay) > 0) {
					new AlertDialog.Builder(MEExpenseListSearch.this).setTitle("알림").setMessage("조회기간이 잘못 설정되었습니다.")
							.setPositiveButton("OK", null).show();
				} else if (("-- 선택 --".equals(pjtCode))) {
					new AlertDialog.Builder(MEExpenseListSearch.this).setTitle("알림").setMessage("프로젝트를 선택하여 주십시오.")
							.setPositiveButton("OK", null).show();
				}
				// else if : 날짜가 아닌 이상한 글자 또는 숫자 또는 8자리이상 숫자 입력오류 - 날짜 형식이 맞지 않습니다.
				else {
					Intent expI = new Intent(MEExpenseListSearch.this, SocketClientService.class);
					expI.putExtra("id", 42); // 기능 분류(비용정산관리:조회)
					expI.putExtra("myId", myId);
					expI.putExtra("startDate", fromDay);
					expI.putExtra("endDate", toDay);
					expI.putExtra("projectCode", pjtCode);
					expI.putExtra("accountCode", acntCode);
					expI.putExtra("accountName", selectedAcnt);
					expI.putExtra("loginAddr", addr);
					expI.putExtra("loginPort", port);
					expI.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
					startService(expI);
					finish();
				}
			}
		});
	}

	protected void search() {
		String strStartDate = startDate.getText().toString();
		String strEndDate = endDate.getText().toString();

		new AlertDialog.Builder(MEExpenseListSearch.this).setTitle("INPUT STR CHECK").setMessage(strStartDate + " " + strEndDate)
				.setPositiveButton("OK", null).show();
	}

	/**
	 * <b>메소드 :</b> <b>onCreateDialog</b>
	 * <p>
	 * <ul>
	 * <li>날짜 다이얼로그를 생성
	 * <li>메소드에 대한 설명2
	 * </ul>
	 * </p>
	 * 
	 * @since 2012. 8. 14.
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		if (id == DATE_DIALOG_CALENDAR_START) {
			return new DatePickerDialog(this, mDateSetListener_start, mYear, mMonth, mDay);
		} else if (id == DATE_DIALOG_CALENDAR_END) {
			return new DatePickerDialog(this, mDateSetListener_end, mYear, mMonth, mDay);
		}
		return null;
	}

	// 날짜입력 위젯 설정버튼 클릭 이벤트 처리(파라미터 변수저장, 에딧텍스트 데이터 전달)-from
	private DatePickerDialog.OnDateSetListener mDateSetListener_start = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			startDate.setText(new StringBuilder().append(mYear).append(MEDateHandler.pad(mMonth + 1))// Month is 0 based so add 1
					.append(MEDateHandler.pad(mDay)));
		}
	};
	// 날짜입력 위젯 설정버튼 클릭 이벤트 처리(파라미터 변수저장, 에딧텍스트 데이터 전달)-to
	private DatePickerDialog.OnDateSetListener mDateSetListener_end = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			endDate.setText(new StringBuilder().append(mYear).append(MEDateHandler.pad(mMonth + 1)).append(MEDateHandler.pad(mDay)));
		}
	};

}
